﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ParserGenerator.ParserConstruction
{
    [Serializable]
    public sealed class ParserAutomatonStatePredecessorsTable : ReadOnlyDictionary<ParserAutomatonState, ParserAutomatonStatePredecessors>
    {
        internal ParserAutomatonStatePredecessorsTable(ParserAutomatonStateTable states)
            : base(new Dictionary<ParserAutomatonState, ParserAutomatonStatePredecessors>())
        {
            if (states == null)
                throw new ArgumentNullException(nameof(states));
            foreach (ParserAutomatonState state in states)
                foreach (var t in state.Transitions.Values)
                    this[t.Target].Add(state);
        }

        public new ParserAutomatonStatePredecessors this[ParserAutomatonState state]
        {
            get
            {
                if (state == null)
                    throw new ArgumentNullException(nameof(state));
                ParserAutomatonStatePredecessors predecessors;
                if (!Dictionary.TryGetValue(state, out predecessors))
                {
                    predecessors = new ParserAutomatonStatePredecessors();
                    Dictionary.Add(state, predecessors);
                }
                return predecessors;
            }
        }
    }
}
